package com.zhang;

import java.util.Iterator;

public class MyArrayList<E> {
    private Object[] table;
    private int size;

    public MyArrayList() {
        this.table = new Object[10];
        size = 0;
    }

    public int size() {
        return size;
    }

    public class MyIterator<E> implements Iterator {

        private int cursor;
        int lastRet = -1;


        public boolean hasNext() {
            if (cursor < size) {
                return true;
            }
            return false;
        }


        public Object next() {
            Object[] itList = table;
            Object o = itList[cursor];
            if (cursor >= size)
                throw new RuntimeException("光标的元素为空");
            cursor++;
            return o;
        }

    }

    public String toString() {
        String str = "[";
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                str += table[i] + "]";
            } else {
                str += table[i] + ",";
            }
        }
        return str;
    }

    public boolean add(E e) {
        add(e, table, size);
        return true;
    }

    private void add(E e, Object[] table, int size) {
        if (size >= table.length) {
            reSize(e);
        } else {
            table[size] = e;
            this.size++;
        }
    }

    private void reSize(E e) {
        Object[] newTable = new Object[table.length + table.length / 2];
        for (int i = 0; i < table.length; i++) {
            newTable[i] = table[i];
        }
        newTable[table.length] = e;
        this.table = newTable;
    }

    int length() {
        return table.length;
    }

    public E remove(Object o) {
        Object res = null;
        int index = -1;
        for (int i = 0; i < table.length - 1; i++) {
            if (table[i] == o) {
                index = i;
                res = table[i];
            }
            if (index != -1) {
                table[i] = table[i + 1];
            }
        }
        if (index != -1) {
            size = size - 1;
            return (E) res;
        }
        return null;
    }

    public E get(int index) {
//        System.out.println("index: "+index);
//        System.out.println("size"+size);
        if (index >= size) {
            throw new RuntimeException("索引越界了，索引为：" + index + " , 数组的长度为：" + size);
        }
        return (E) table[index];
    }

    public void add(int index, E element) {

    }

}
